package com.xxxx.microservice.forestry.component;

import com.supermap.analyst.spatialanalyst.InterpolationKrigingParameter;
import com.supermap.analyst.spatialanalyst.Interpolator;
import com.supermap.analyst.spatialanalyst.SearchMode;
import com.supermap.analyst.spatialstatistics.*;
import com.supermap.data.*;
import com.xxxx.microservice.forestry.dto.result.ClusterResult;
import com.xxxx.microservice.forestry.dto.result.QueryResult;
import com.xxxx.microservice.forestry.dto.result.AutoCorrelationResult;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Component
public class SuperMapCom {

    @Value("${workspace.smwu-path}")
    private String smwuPath;

    // 插值
    public synchronized void interpolate(String filter, String filed) {
        Workspace m_workspace = new Workspace();
        DatasetVector datasetVector = getDatasetVector(m_workspace);
        Datasource datasource = datasetVector.getDatasource();

        String filterName = "interpolate_filter";
        DatasetVector filterVector = filterAndCreate(datasetVector, filterName, filter);

        InterpolationKrigingParameter parameter = new InterpolationKrigingParameter();
        parameter.setSearchMode(SearchMode.KDTREE_FIXED_COUNT);
        parameter.setExpectedCount(5);
        parameter.setResolution(9000);
        parameter.setBounds(filterVector.computeBounds());

        String resultName = "interpolate_result";
        datasource.getDatasets().delete(resultName);
        DatasetGrid m_datasetResult = Interpolator.interpolate(parameter, filterVector,
                filed, 1, datasource, resultName, PixelFormat.SINGLE);

        System.out.println("克吕金插值栅格结果范围：" + m_datasetResult.getBounds());

        datasource.getDatasets().delete(filterName);
        datasource.getDatasets().delete(resultName);
        m_workspace.dispose();
    }

    // 聚类
    public synchronized List<ClusterResult> clusterOutlierAnalyst(String filter, String filed) {
        Workspace m_workspace = new Workspace();
        DatasetVector datasetVector = getDatasetVector(m_workspace);
        Datasource datasource = datasetVector.getDatasource();

        String filterName = "cluster_filter";
        DatasetVector filterVector = filterAndCreate(datasetVector, filterName, filter);
        Map<Integer, Feature> allFeatures = filterVector.getAllFeatures();

        PatternsParameter patternsParameter = new PatternsParameter();
        patternsParameter.setAssessmentFieldName(filed);

        String resultName = "cluster_result";
        datasource.getDatasets().delete(resultName);
        DatasetVector result = ClusteringDistributions.clusterOutlierAnalyst(
                filterVector,
                datasource,
                resultName,
                patternsParameter);

        List<ClusterResult> results = new ArrayList<>();
        if (result != null) {
            for (Map.Entry<Integer, Feature> integerFeatureEntry : result.getAllFeatures().entrySet()) {
                Feature feature = integerFeatureEntry.getValue();
                Feature originalFeature = allFeatures.get(integerFeatureEntry.getKey());
                ClusterResult clusterResult = new ClusterResult();
                clusterResult.setYdbh(originalFeature.getString("YDBH"));
                GeoPoint geometry = (GeoPoint) feature.getGeometry();
                clusterResult.setJd(geometry.getX());
                clusterResult.setWd(geometry.getY());
                clusterResult.setZldwdm(originalFeature.getString("ZLDWDM"));
                clusterResult.setZldwmc(originalFeature.getString("ZLDWMC"));
                clusterResult.setField(originalFeature.getString(filed));
                clusterResult.setMoranI(feature.getDouble("ALMI_MoranI"));
                clusterResult.setZscore(feature.getDouble("ALMI_Zscore"));
                clusterResult.setPvalue(feature.getDouble("ALMI_Pvalue"));
                clusterResult.setType(feature.getString("ALMI_Type"));
                results.add(clusterResult);
            }
        }

        datasource.getDatasets().delete(filterName);
        datasource.getDatasets().delete(resultName);
        m_workspace.dispose();

        return results;
    }


    /**
     * 相关性
     */
    public AutoCorrelationResult autoCorrelation (String filter, String filed) {
        Workspace m_workspace = new Workspace();
        DatasetVector datasetVector = getDatasetVector(m_workspace);
        Datasource datasource = datasetVector.getDatasource();

        String filterName = "cluster_filter";
        DatasetVector filterVector = filterAndCreate(datasetVector, filterName, filter);

        PatternsParameter patternsParameter = new PatternsParameter();
        patternsParameter.setAssessmentFieldName(filed);

        AnalyzingPatternsResult result = AnalyzingPatterns.autoCorrelation(filterVector,patternsParameter);
        // AnalyzingPatternsResult pz = AnalyzingPatterns.averageNearestNeighbor(filterVector, 0, DistanceMethod.EUCLIDEAN);

        // System.out.println(pz);
        AutoCorrelationResult results = new AutoCorrelationResult();
        results.setExpectation(result.getExpectation());
        results.setMoranI(result.getIndex());
        results.setPvalue(result.getPValue());
        results.setZscore(result.getZScore());
        results.setVariance(result.getVariance());
        return results;
    }

	/**
	 * 空间叠加查询
	 * @param datasetName ： 查询对象数据集名称
	 * @param queryAttribute ： 查询条件
	 * @return
	 */
    public List<QueryResult> spatialQuery(String datasetName, String queryAttribute) {
    	List<QueryResult> queryResult = new ArrayList<QueryResult>();
    	Workspace m_workspace = new Workspace();
    	if(this.openWorkSpace(m_workspace)) {
    		//打开数据源
    		Datasource datasource = m_workspace.getDatasources().get("业务数据");
    		Datasets datasets = datasource.getDatasets();
    		//查询对象数据集
    		DatasetVector  srctDatasetVector = (DatasetVector) datasets.get(datasetName);
    		//查询目标数据集
    		DatasetVector  targetDatasetVector = (DatasetVector) datasets.get("平谷园林草地样点评价_1");
    		
    		//从查询对象按条件构建记录集  Substr( TDLYLX, 0, 3)
    		Recordset srcRecordset = srctDatasetVector.query(queryAttribute, CursorType.STATIC); //
    		System.out.println("查询对象数量：" + srcRecordset.getRecordCount());
    		
    		// 设置查询参数
            QueryParameter parameter = new QueryParameter();
            //parameter.setAttributeFilter("SmID<100");
            parameter.setCursorType(CursorType.STATIC);
            parameter.setSpatialQueryMode(SpatialQueryMode.CONTAIN);
            parameter.setSpatialQueryObject(srcRecordset);
            
           // 进行查询
            Recordset recordset = targetDatasetVector.query(parameter);
            System.out.println("查询结果数量2：" + recordset.getRecordCount());
            
            while (!recordset.isEOF()) {
            	QueryResult result = new QueryResult();
//            	result.setBsm(recordset.getFieldValue("BSM").toString());
            	result.setYdbh(recordset.getFieldValue("ydbh").toString());
//            	result.setJd(recordset.getFieldValue("jd").toString());
//            	result.setWd(recordset.getFieldValue("wd").toString());
//            	result.setYsdm(recordset.getFieldValue("YSDM").toString());
//            	result.setYdlb(recordset.getFieldValue("YDLB").toString());
//            	result.setCylx(recordset.getFieldValue("CYLX").toString());
//            	result.setSfcjswxdtjt(recordset.getFieldValue("SFCJSWXDTJT").toString());
//            	result.setZldwdm(recordset.getFieldValue("zldwdm").toString());
//            	result.setZldwmc(recordset.getFieldValue("zldwmc").toString());
//            	result.setPd(recordset.getFieldValue("pd").toString());
//            	result.setTdlylx(recordset.getFieldValue("tdlylx").toString());
//            	result.setTrlxbm(recordset.getFieldValue("trlxbm").toString());
//            	result.setTl(recordset.getFieldValue("tl").toString());
//            	result.setTs(recordset.getFieldValue("ts").toString());
//            	result.setTz(recordset.getFieldValue("tz").toString());

            	queryResult.add(result);
                recordset.moveNext();
            }
            recordset.close();
            recordset.dispose();
            datasource.close();
            m_workspace.close();
            m_workspace.dispose();
    		
    	} else {
    		System.out.println("打开工作空间失败！ ");
    	}
        
    	return queryResult;
       
    }
    
    private  boolean openWorkSpace(Workspace workspace) { 
    	WorkspaceConnectionInfo conInfo = new WorkspaceConnectionInfo(smwuPath);
		// 定义连接工作空间的类型为 SMWU
        conInfo.setType(WorkspaceType.SMWU);
		if (workspace.open(conInfo)) {
			System.out.println("打开工作空间成功！ ");
			return true;
		} else {
			System.out.println("打开工作空间失败！ ");
			return false;
		}
	}
    
    private DatasetVector getDatasetVector(Workspace m_workspace) {
        WorkspaceConnectionInfo conInfo = new WorkspaceConnectionInfo(smwuPath);
        conInfo.setType(WorkspaceType.SMWU);
        m_workspace.open(conInfo);
        Datasource datasource = m_workspace.getDatasources().get(1);
        return (DatasetVector) datasource.getDatasets().get("平谷园林草地样点评价");
    }

    private DatasetVector filterAndCreate(DatasetVector sourceVector, String targetName, String filter) {
        if (filter == null || filter.isEmpty()) {
            return sourceVector;
        }
        FieldInfo[] fieldInfos = sourceVector.getFieldInfos().toArray();
//        FieldInfo[] newFieldInfos = new FieldInfo[4];
//        newFieldInfos[0] = fieldInfos[3];
//        newFieldInfos[1] = fieldInfos[4];
//        newFieldInfos[2] = fieldInfos[5];
//        newFieldInfos[3] = fieldInfos[6];
        FieldInfo[] newFieldInfos = Arrays.copyOfRange(fieldInfos, 4, fieldInfos.length);

        Datasets datasets = sourceVector.getDatasource().getDatasets();
        if (datasets.contains(targetName)) {
            datasets.delete(targetName);
        }
        DatasetVectorInfo info = new DatasetVectorInfo(targetName, DatasetType.POINT);
        DatasetVector dataset = datasets.create(info);
        dataset.getFieldInfos().addRange(newFieldInfos);
        dataset.append(sourceVector.query(filter, CursorType.STATIC));
        return dataset;
    }

}
